package com.mesnac.filemgr.entity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import com.mesnac.comm.sysinfo.SysInfo;

/**
 * 创建目录，解析目录
 * 
 * @author chilei
 * 
 */
public class DirMgr {

	private static final String inforFileName = "abceddecba.data";
	private static final String rootPath = SysInfo.rootpath;

	/**
	 * 初始化
	 * 
	 * @param path
	 * @throws Exception
	 */
	public static void dirInit(String path) throws Exception {
		DirectoryInfor result = new DirectoryInfor();

		File file = new File(path);
		String[] filea = path.split("\\" + File.separator);
		String tName = filea[filea.length - 1];
		// System.out.println(tName);
		File[] subFile = file.listFiles();
		List<DirectoryInfor> dirList = new ArrayList<DirectoryInfor>();
		List<FileInfor> fileList = new ArrayList<FileInfor>();
		if (subFile != null) {
			for (int i = 0; i < subFile.length; i++) {

				// 目录or文件
				if (subFile[i].isDirectory()) {
					// System.out.println(subFile[i]);
					String[] tmpInfor = subFile[i].toString().split(
							"\\" + File.separator);
					DirectoryInfor tmp = new DirectoryInfor();
					if (tmpInfor.length > 0) {
						String dirName = tmpInfor[tmpInfor.length - 1];
						tmp.setDirName(dirName);
					}

					tmp.setDirPath(subFile[i].toString());
					dirList.add(tmp);

				} else {

				}
			}
			result.setDirList(dirList);
			result.setDirName(tName);
			result.setDirPath(path);
		}
		// 文件流
		FileOutputStream outstream = new FileOutputStream(path + File.separator
				+ inforFileName);
		ObjectOutputStream out = new ObjectOutputStream(outstream);
		out.writeObject(result);
		out.close();

	}

	/**
	 * 反序列化
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static synchronized DirectoryInfor dirDeserialize(String path)
			throws Exception {
		File abcde = new File(path + File.separator + inforFileName);
		if (!abcde.exists()) {
			dirInit(path);
		}
		FileInputStream instream = new FileInputStream(path + File.separator
				+ inforFileName);
		ObjectInputStream in = new ObjectInputStream(instream);
		DirectoryInfor result = (DirectoryInfor) in.readObject();

		return result;
	}

	/**
	 * 往已有的目录中增加目录
	 * 
	 * @param parentPath
	 * @param dirName
	 * @throws Exception
	 */
	public synchronized static boolean addDir(String parentPath, String dirName)
			throws Exception {
		//System.out.println("Thread====>"+Thread.currentThread().getName());
		//System.out.println(System.currentTimeMillis());
		DirectoryInfor root = DirMgr.dirDeserialize(parentPath);
		DirectoryInfor child = new DirectoryInfor();
		child.setDirName(dirName);
		child.setDirPath(parentPath + File.separator + dirName);
		if (root.getDirList() != null) {
			boolean flag = false;
			for(int i = 0; i < root.getDirList().size(); i++){
				if(root.getDirList().get(i).getDirName().equals(dirName)){
					flag = true;
					break;
				}
			}
			if (!flag)
				root.getDirList().add(child);
			else
				return false;
		}

		else {
			List<DirectoryInfor> newList = new ArrayList<DirectoryInfor>();
			if (!newList.contains(child))
				newList.add(child);
			root.setDirList(newList);
		}
		// 创建文件夹
		File dir = new File(parentPath + File.separator + dirName);
		if (!dir.exists())
			dir.mkdir();
		// System.out.println(Thread.currentThread().getName()+"::::");
		// Thread.sleep(5000);
		// System.out.println(Thread.currentThread().getName()+"::::");
		// 文件流
		FileOutputStream outstream = new FileOutputStream(parentPath
				+ File.separator + inforFileName);
		ObjectOutputStream out = new ObjectOutputStream(outstream);
		out.writeObject(root);
		out.close();
		//Thread.sleep(5000);
		return true;
	}

	/**
	 * 往已有目录中添加文件
	 * 
	 * @param parentPath
	 * @param file
	 * @throws Exception
	 */
	public synchronized static boolean addFile(String parentPath, FileInfor file)
			throws Exception {
		DirectoryInfor root = DirMgr.dirDeserialize(parentPath);
		if (root.getFileList() != null) {
			boolean flag = false;
			for(int i = 0; i < root.getFileList().size(); i++){
				if(root.getFileList().get(i).getFileName().equals(file.getFileName())){
					flag = true;
					break;
				}
			}
			if (!flag)
				root.getFileList().add(file);
			else
				return false;
		} else {
			List<FileInfor> newList = new ArrayList<FileInfor>();
			if (!newList.contains(file))
				newList.add(file);
			root.setFileList(newList);
		}
		// 文件流
		FileOutputStream outstream = new FileOutputStream(parentPath
				+ File.separator + inforFileName);
		ObjectOutputStream out = new ObjectOutputStream(outstream);
		out.writeObject(root);
		out.close();
		return true;
	}

	/**
	 * 删除一个文件
	 * 
	 * @param parentPath
	 * @param filename
	 * @throws Exception
	 */
	public synchronized static boolean delFile(String parentPath, String filename)
			throws Exception {
		DirectoryInfor root = DirMgr.dirDeserialize(parentPath);
		if (root.getFileList() == null)
			return false;
		List<FileInfor> tmp = root.getFileList();
		for (int i = 0; i < tmp.size(); i++) {
			if (tmp.get(i).getFileName().equals(filename)) {
				tmp.remove(i);
				break;
			}
		}
		root.setFileList(tmp);

		// 文件流
		FileOutputStream outstream = new FileOutputStream(parentPath
				+ File.separator + inforFileName);
		ObjectOutputStream out = new ObjectOutputStream(outstream);
		out.writeObject(root);
		out.close();
		return true;
	}

	/**
	 * 删除目录
	 * 
	 * @param parentPath
	 * @param dirname
	 * @throws Exception
	 */
	public synchronized static boolean delDir(String parentPath, String dirname)
			throws Exception {
		// System.out.println(Thread.currentThread().getName()+"::::");
		DirectoryInfor root = DirMgr.dirDeserialize(parentPath);
		if (root.getDirList() == null) {
			return false;
		}
		List<DirectoryInfor> tmp = root.getDirList();
		for (int i = 0; i < tmp.size(); i++) {
			if (tmp.get(i).getDirName().equals(dirname)) {
				tmp.remove(i);
				break;
			}
		}
		root.setDirList(tmp);

		
		// System.out.println(Thread.currentThread().getName()+"::::");
		// 文件流
		FileOutputStream outstream = new FileOutputStream(parentPath
				+ File.separator + inforFileName);
		ObjectOutputStream out = new ObjectOutputStream(outstream);
		out.writeObject(root);
		out.close();
		return true;
	}

	/**
	 * 对文件进行下载
	 * 
	 * @param parentPath
	 * @param filename
	 * @throws Exception
	 */
	public synchronized static boolean downloadFile(String parentPath,
			String filename) throws Exception {
		DirectoryInfor root = DirMgr.dirDeserialize(parentPath);
		if (root.getFileList() == null)
			return false;
		List<FileInfor> tmp = root.getFileList();
		for (int i = 0; i < tmp.size(); i++) {
			if (tmp.get(i).getFileName().equals(filename)) {
				tmp.get(i).setDownloadtimes(tmp.get(i).getDownloadtimes() + 1);
			}
		}
		root.setFileList(tmp);
		// 文件流
		FileOutputStream outstream = new FileOutputStream(parentPath
				+ File.separator + inforFileName);
		ObjectOutputStream out = new ObjectOutputStream(outstream);
		out.writeObject(root);
		out.close();
		return true;
	}

	/**
	 * 上传新版本
	 * 
	 * @param parentPath
	 * @param oldfilename
	 * @param newfilename
	 * @throws Exception
	 */
	public synchronized static boolean uploadNewFile(String parentPath,
			String oldfilename, FileInfor newfilename) throws Exception {

		DirectoryInfor root = DirMgr.dirDeserialize(parentPath);
		if (root.getFileList() == null)
			return false;
		List<FileInfor> tmp = root.getFileList();
		for (int i = 0; i < tmp.size(); i++) {
			if (tmp.get(i).getFileName().equals(oldfilename)) {
				tmp.get(i).setFileName(newfilename.getFileName());
				tmp.get(i).setFilemaster(newfilename.getFilemaster());
				tmp.get(i).setDescribe(newfilename.getDescribe());
				tmp.get(i).setFileSize(newfilename.getFileSize());
				tmp.get(i).setKeywords(newfilename.getKeywords());
				tmp.get(i).setUploadtime(newfilename.getUploadtime());
				tmp.get(i).setVersion(tmp.get(i).getVersion() + 1);
				tmp.get(i).setVersionDescribe(newfilename.getVersionDescribe());
			}
		}
		root.setFileList(tmp);
		
		// 文件流
		FileOutputStream outstream = new FileOutputStream(parentPath
				+ File.separator + inforFileName);
		ObjectOutputStream out = new ObjectOutputStream(outstream);
		out.writeObject(root);
		out.close();
		return true;
	}

	/**
	 * 将目录文件夹结构转换成json
	 * 
	 * @param parentPath
	 * @return
	 * @throws Exception
	 */
	public static JSONArray getJsonDirByPath(String parentPath)
			throws Exception {
		DirectoryInfor root = DirMgr.dirDeserialize(parentPath);
		List a = root.getDirList();
		JSONArray jsonArray = JSONArray.fromObject(a);
		return jsonArray;
	}

	public static void main(String args[]) throws Exception {

		new Thread() {
			public void run() {
				try {
					long start = System.currentTimeMillis();
					
					DirMgr.addDir("D:\\pinshuo\\项目管理\\科伯利","材料价格库");
					//long end = System.currentTimeMillis();
					//System.out.println(end-start);
					//DirMgr.addDir("D:\\pinshuo\\项目管理","造价信息库");
					//DirMgr.addDir("D:\\pinshuo\\资源库","招标信息库");
					//DirMgr.addDir("D:\\pinshuo\\资源库","规范规程图集");
					// DirMgr.addDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","莱西品烁华年");
					// DirMgr.addDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","胶州品烁华年");
					// DirMgr.addDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","科伯利");
				} catch (Exception e) {

				}

			}
		}.start();
		new Thread() {
			public void run() {
				try {

					 //DirMgr.delDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo","test1");
					// DirMgr.delDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","橡塑新材料科学研究院");
					// DirMgr.delDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","胶州装备产业园");
					// DirMgr.delDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","莱西品烁华年");
					// DirMgr.delDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","胶州品烁华年");
					// DirMgr.delDir("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo\\项目管理","科伯利");
				} catch (Exception e) {

				}

			}
		}.start();
		
		  DirectoryInfor root = DirMgr.dirDeserialize(rootPath+"\\项目管理");
		  for(int i = 0; i < root.getDirList().size(); i++){
			  System.out.println(root.getDirList().get(i).getDirPath());
		  }
		 //for(int i = 0; i < root.getFileList().size(); i++){
		 //System.out.println(root.getFileList().get(i).getFileName()+root.getFileList().get(i).getFilePath()); }
		 
		//DirMgr.dirInit(rootPath+"\\项目管理");
		//JSONArray ja = DirMgr
				//.getJsonDirByPath("D:\\workspace\\pinshuoinfor\\WebRoot\\pinshuo");
		//System.out.println(ja);
		// DirMgr.dirInit(path);
		// DirMgr.dirDeserialize(path);
	}
}
